//
//  ZMAD.swift
//  zhonglibang
//
//  Created by Rowling on 2021/5/28.
//
import Foundation
import RxSwift
import UIKit
//import Leto

class ZMADManager : NSObject {
    enum ADSlot : String {
        // 早安签到
        case morning     = "948571159"
        // 打卡工作
        case onWorking   = "948574096"
        // 努力工作
        case keepOnGoing = "948574104"
        // 下班打卡
        case offWork     = "948574112"
        // 每次分享
        case share       = "948574118"
    }
    
    enum ADLoveSlot : String {
        // love
        case love1 = "948599289"
        // love
        case love2 = "948599300"
        // love
        case love3 = "948599309"
        // love
        case love4 = "948599316"
        // love
        case love5 = "948599325"
    }
    
    enum ADLoveFarmerTask : String {
        // love
        case farmer1 = "948599392"
    }
    
    
    
    var taskList = [
        ADLoveSlot.love1.rawValue,
        ADLoveSlot.love2.rawValue,
        ADLoveSlot.love3.rawValue,
        ADLoveSlot.love4.rawValue,
        ADLoveSlot.love5.rawValue,
        ADSlot.morning.rawValue,
        ADSlot.onWorking.rawValue,
        ADSlot.keepOnGoing.rawValue,
        ADSlot.offWork.rawValue,
        ADSlot.share.rawValue,
    ]
    
    

    static let shard = ZMADManager()
    /// 小说对象
//    var novelAd : OSETNovelAd!
    /// 短视频获取奖励时间
//    var shortVideoTime = 10
    /// 咨询获取奖励时间
//    var consultTime = 5

    var disposeable : Disposable?

    var disposeBag = DisposeBag()
    
    let AD_BANNER_KEY = "ad_banner_key"
    let AD_VIDEO_KEY = "ad_video_key"
    let AD_SPLASH_KEY = "ad_splash_key"
    let AD_SDK_KEY = "ad_sdk_key"
    
    /// 激励视频广告
//    var rewardVideoAd: ZMVideoAd?
    
    var complete : (()->())?
    var start : (()->())?
    var failed : ((_ error : Error?)->())?
    /// 广告sdk key
    var key : String {
        get {
            return "41B13D7C811946FF"
        }
    }

    
    func saveKeys(dic : [String : String]) {
        let json = JSON(dic)
        let banner = json["banner"].stringValue
        let video = json["video"].stringValue
        let splash = json["splash"].stringValue
        let sdk = json["sdk"].stringValue
        UserDefaults.standard.set(banner, forKey: AD_BANNER_KEY)
        UserDefaults.standard.set(video, forKey: AD_VIDEO_KEY)
        UserDefaults.standard.set(splash, forKey: AD_SPLASH_KEY)
        UserDefaults.standard.set(sdk, forKey: AD_SDK_KEY)
    }

//    public func requestAuthCode(_ id: String, _ showLoad: Bool = false) {
//        let param = ["id":id, "userId":ZMAppShareData.share.userID, "type":"TASK"]
//        if showLoad {
//            ZMToast.showActivity()
//        }
//        ZMAPIManage<String>().sendReqeust(method: ZMUserAPI.create_auth_code(param)) { (resp) in
//            if resp.code == .success {
//                if let data = resp.data {
//                    let codeStr = AppHelper.generalOrder(userId: ZMAppShareData.share.userID, randomKey: ZMAppShareData.share.loginInfo!.randomKey, showId: ZMAppShareData.share.user!.showId, time: data.zm.hk_toInt(), type: "TASK", id: id)
//                    self.requestFinishTask(id, codeStr)
//                }
//            }
//        }
//    }

    func requestFinishTask(_ id: String, _ code: String) {
//        let param = ["taskId": id, "userId": ZMAppShareData.share.userID, "code":code]
//        ZMADAPI.taskComplete(param).rxRequest(type: String.self).subscribe(onNext:{ [unowned self] resp in
//            print("广告奖励领取成功")
////            ZMToast.hiddenActivity()
//            ZMToast.showToast(title: "您已成功获取\(resp)积分")
//        }).disposed(by: disposeBag)
    }

//    func registerGame() {
//        let login : MgcCustomLogin = { vc, call in
//            call(true,{
//                return [mgc_sync_userid_key : "123",
//                       mgc_sync_portrait_key:"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2175843469,2158546651&fm=26&gp=0.jpg",
//                       mgc_sync_nickname_key:"昵称",
//                       mgc_sync_loginsign_key:"1"]
//            },{ isSyncSuccess, msg, mgc_userId in
//                print(msg)
//            })
//        }
//
//        let info = [mgc_app_id_key:"364362", mgc_register_login_key : login] as [AnyHashable : Any]
//        MGCMiniGameApi.mgc_initSdk(withInfo: info)
//    }

//    func goGame(vc:UIViewController) {
//        MGCMiniGameApi.mgc_open(URL.init(string: "mgcgame://mgc.com/gamecenter"), vc: vc)
//    }
    
    
   //MARK: KSAD------
    func register() {
//        OSETManager.configure(key)
    }
    
}

// 扩展快速调用的方法
extension ZMADManager : ZMVideoAdDelegate {
    
    // 看视频
    public func showZMVideoAd(vc:UIViewController,
                              slot: String,
                              start:@escaping  (()->()),
                               complete:@escaping  (()->()),
                               failed:@escaping  ((_ error:Error?)->())) {
//        if (rewardVideoAd != nil) {
//            ZMToast.hiddenActivity()
//            print("播放重复--当前广告正在播放中...")
//            return
//        }
        self.start = start
        self.complete = complete
        self.failed = failed
        if skipAd {
            // 跳过广告
            start()
            complete()
            return
        }
//        rewardVideoAd = ZMVideoAd(delegate: self,fromRootViewController:vc)
//        rewardVideoAd?.showAd()
        playSelfAd(vc: vc)
    }
    
    // 易农自有广告
    func playSelfAd(vc : UIViewController) {
        CommonAPI.ad.rxRequest(type: String.self).subscribe(onNext:{ [unowned self] resp in
            if let start =  self.start{
                start()
            }
            let advc = ADController()
            advc.onHandClose = {
                if let failed = self.failed {
                    failed(ZMError(errorMeg: "未能成功观看"))
                }
            }
            advc.onSuccessClose = complete
            advc.modalPresentationStyle = .fullScreen
            advc.resource = resp
            vc.present(advc, animated: true, completion: nil)
        }, onError: { e in
            if let failed = self.failed {
                failed(e)
            }
        }).disposed(by: disposeBag)
    }

    func rewardVideoDidReceiveSuccess() {
        if let start = self.start {
            start()
        }
    }

    func rewardVideoLoad(_ error: Error?) {
        if let failed = self.failed {
            failed(error!)
        }
        // 如果加载失败就播放自有广告
//        guard let rewardVideoAd = rewardVideoAd else {return}
//        playSelfAd(vc: rewardVideoAd.fromRootViewController)
//        self.rewardVideoAd = nil
    }

    func rewardVideoDidClose() {
//        rewardVideoAd = nil
    }

    func rewardVideoPlayError(_ error: Error?) {
        if let failed = self.failed {
            failed(error!)
        }
//        rewardVideoAd = nil
    }

    func rewardVideo() {
//        self.rewardVideoAd = nil;
        if let complete = self.complete {
            complete()
        }
    }

    func rewardVideoPlayEnd() {
//        rewardVideoAd = nil
    }

    func rewardVideoPlayStart() {

    }
}


//MARK:-------------------视频--------------------
protocol ZMVideoAdDelegate : NSObjectProtocol {
    //广告配置加载完成
    func rewardVideoDidReceiveSuccess()
    // "加载失败"
    func rewardVideoLoad(_ error: Error?)
    //广告已关闭
    func rewardVideoDidClose()
    //播放出错
    func rewardVideoPlayError(_ error: Error?)
    //达到条件
    func rewardVideo()
    // 视频播放结束
    func rewardVideoPlayEnd()
    // 视频开始播放
    func rewardVideoPlayStart()
}
//
//class ZMVideoAd : NSObject {
//    weak var delegate : ZMVideoAdDelegate!
//
////    var rewardVideoAd : OSETRewardVideoAd!
//
//    weak var fromRootViewController : UIViewController!
//    init(delegate:ZMVideoAdDelegate,fromRootViewController:UIViewController) {
//        self.delegate = delegate
//        rewardVideoAd = OSETRewardVideoAd(slotId: "B8B4C5A914C88819C091858026730F34")
//        self.fromRootViewController = fromRootViewController
//    }
//
//    func showAd() {
//        rewardVideoAd.delegate = self
//        rewardVideoAd.loadData()
//    }
//
//    func showVideo() {
//        rewardVideoAd.show(fromRootViewController: fromRootViewController)
//    }
//}

//extension ZMVideoAd : OSETRewardVideoAdDelegate {
//    func rewardVideoDidReceiveSuccess(_ rewardVideoAd: Any, slotId: String) {
//        delegate.rewardVideoDidReceiveSuccess()
//        showVideo()
//    }
//
//    func rewardVideoLoad(toFailed rewardVideoAd: Any, error: Error) {
//        delegate.rewardVideoLoad(error)
//    }
//
//    func rewardVideoDidClose(_ rewardVideoAd: Any, check checkString: String) {
//        delegate.rewardVideoDidClose()
//    }
//
//    func rewardVideoPlayError(_ rewardVideoAd: Any, error: Error) {
//        delegate.rewardVideoPlayError(error)
//    }
//
//    func rewardVideo(onReward rewardVideoAd: Any, check checkString: String) {
//        delegate.rewardVideo()
//    }
//
//    func rewardVideoPlayEnd(_ rewardVideoAd: Any, check checkString: String) {
//        delegate.rewardVideoPlayEnd()
//    }
//
//    func rewardVideoPlayStart(_ rewardVideoAd: Any) {
//        delegate.rewardVideoPlayStart()
//    }
//}

struct ZMError : Error {
    var errorMeg : String
    var localizedDescription: String {
        get{
          errorMeg
        }
    }
}
